import _ from "lodash";
import {useCallback, useEffect, useState} from "react";
import {useNav, useScrollData} from "@/hooks";
import {ApiFindGoodsDetailProps, apiGetGoodsDetail, apiKLCreate, apiFindGoods} from "@/api";
import {getPrice} from "@/utils";
import {Image, Ellipsis, Avatar, Collapse, Tabs, Button, Grid} from "antd-mobile";
import {Container, Icon, Swiper} from "@/components/public";
import GoodsBlock from "@/components/Goods/Block";

import imgs from "@/assets/imgs";
import "./goodsDetail.less";

const GridItem = Grid.Item;

export default function GoodsDetail() {
    const {params} = useNav(["id", "shareUrl", "storeId", "title"]);
    const {id, shareUrl, storeId, title, search} = params;
    const routeParams: ApiFindGoodsDetailProps = {
        goodsId: id,
        title,
        search,
        storeId,
    };

    const [imgSwiper, setImgSwiper] = useState<any[]>([]); //商品主图
    const [goodsInfo, setGoodsInfo] = useState<any>({}); //当前页商品信息
    const [shopInfo, setShopInfo] = useState<any>({}); //推荐商品列表
    const [couponInfo, setCouponInfo] = useState<any>(""); //优惠券信息
    const [linkKinds, setLinkKinds] = useState(""); //相同种类推荐
    const [kl, setKl] = useState<any>({});

    const {data: similarGoods, bottomRefresh} = useScrollData(
        {
            fetch: apiFindGoods,
            params: {q: linkKinds},
        },
        [linkKinds]
    );

    //获取商品详情
    const getDetail = () => {
        apiGetGoodsDetail(routeParams)
            .then((res: any) => {
                const {shopInfo, couponInfo, dtlInfo} = res.data;
                const url = dtlInfo.coupon_share_url
                    ? dtlInfo.coupon_share_url
                    : shareUrl
                    ? shareUrl
                    : dtlInfo.item_url;
                setShopInfo(shopInfo || "");
                setCouponInfo(couponInfo || "");
                setGoodsInfo(dtlInfo);
                setImgSwiper(dtlInfo.small_images?.string || [dtlInfo.pict_url]);
                setLinkKinds(dtlInfo.cat_leaf_name);
                createKL(url);
            })
            .catch(err => console.log(err));
    };

    //生成口令
    const createKL = (str: string) => {
        apiKLCreate(str)
            .then((result: any) => {
                const KL = result.data?.tbk_tpwd_create_response?.data || {};
                setKl(KL);
            })
            .catch(err => {
                console.log(err);
            });
    };

    const copyKL = useCallback(() => {
        // Taro.setClipboardData({
        //     data: kl.model || goodsInfo.item_url,
        //     success: function () {
        //         const desc = "优惠券领取成功,请前往淘宝使用";
        //         Taro.showToast({title: desc, icon: "none"});
        //     },
        //     fail: (res) => {
        //         console.log(res);
        //         Taro.showToast({title: "领取失败,请联系客服", icon: "none"});
        //     },
        // });
    }, [kl, goodsInfo]);

    // const goHome = () => Taro.switchTab({url: RouterUrl.home});

    // const handleShare = (): any => {
    //     console.log(couponInfo, goodsInfo);
    //     let title = goodsInfo.title;
    //     if (couponInfo && couponInfo?.coupon_amount) {
    //         const oldPrice = Number(goodsInfo.zk_final_price).toFixed(1);
    //         const newPrice = Number(getPrice(oldPrice, couponInfo.coupon_amount)).toFixed(1);
    //         const ticket = Number(couponInfo.coupon_amount).toFixed(0);
    //         const kind = goodsInfo.cat_leaf_name;
    //         const nick = goodsInfo.nick;
    //         title = `速领${ticket}元!!! 原价${goodsInfo.zk_final_price}元现仅需${newPrice}元${nick}${kind}`;
    //     }

    //     const shareUrl = RouterUrl.goodsDetail + "?" + routeParamsToUrl(params);
    //     return {
    //         title,
    //         path: shareUrl,
    //         imageUrl: goodsInfo.pict_url,
    //     };
    // };

    useEffect(() => {
        getDetail();
    }, [params]);

    const [list, setList] = useState([]);

    useEffect(() => {
        // 初始化列数和列高度
        const numColumns = 2; // 列数
        const columnHeights = Array.from({length: numColumns}, () => 0);
        // 分配商品到列中
        const columnData = similarGoods.map(item => {
            // 找到高度最小的列
            const minHeight = Math.min(...columnHeights);
            const columnIndex = columnHeights.indexOf(minHeight);

            // 计算商品的位置
            const left = `${(columnIndex * 100) / numColumns}%`; // 列宽度
            const top = minHeight;

            // 更新列的高度
            columnHeights[columnIndex] += item.height;

            return {
                ...item,
                position: "absolute",
                left,
                top: `${top}px`,
            };
        });
        // 设置列数据
        setList(columnData);
    }, [similarGoods]);

    return (
        <Container className="page-goodsDetail">
            <>
                <Swiper autoplay loop data={imgSwiper} />
                <div className="goods_info wrapper">
                    <div className="line ">
                        <div className="fl flex">
                            <div className="txt">券后约￥</div>
                            <div className="zk_final_price">
                                {goodsInfo.zk_final_price
                                    ? getPrice(goodsInfo.zk_final_price, couponInfo.coupon_amount)
                                    : ""}
                            </div>
                            {couponInfo.coupon_amount ? (
                                <div className="reserve_price">￥{goodsInfo.zk_final_price}</div>
                            ) : (
                                ""
                            )}
                        </div>
                        <div className="share">月销：{goodsInfo.volume}</div>
                    </div>
                    <div className="line2">
                        <Ellipsis direction="end" rows={2} content={goodsInfo.title} className="title" />
                    </div>
                    <div className="yhq-box">
                        <Image className="yhq flex" src={imgs.detail.yhqbg} />
                        <div className="info-box flex">
                            <div className="coupon-box ">
                                <div className="price">￥{couponInfo.coupon_amount}</div>
                                <div className="date">
                                    {couponInfo.coupon_start_time}-{couponInfo.coupon_end_time}
                                </div>
                            </div>
                            <div className="hint" onClick={copyKL}>
                                免费领取
                            </div>
                        </div>
                    </div>
                    <div className="line3">
                        <div className=" reminder">
                            注意：商品价格以淘宝价格为准。且本平台不提供支付购买，领券后请到对应平台下单。
                            复制口令后到淘宝打开即可使用。
                        </div>
                    </div>

                    <div className="shop-box">
                        <div className="shop-info flex">
                            <div className="flex">
                                <Avatar className="pict" src={shopInfo.pict_url} />
                                <div className="shop-tit">{shopInfo.shop_title}</div>
                            </div>
                            <div className="flex goShop">
                                进入店铺
                                <Icon className="icon-jinrujiantouxiao" size={16}></Icon>
                            </div>
                        </div>
                        <Collapse
                            accordion
                            className="collapse-wrapper"
                            arrow={active => (
                                <Icon className={`icon-xiajiantou- ${active ? "adm-collapse-arrow-active" : ""}`} />
                            )}
                        >
                            <Collapse.Panel key="1" title="图文详情">
                                {imgSwiper.map(item => (
                                    <Image className="w100" key={item} src={item} fit="cover" />
                                ))}
                            </Collapse.Panel>
                        </Collapse>
                    </div>
                </div>
                <Tabs>
                    <Tabs.Tab title="相似推荐" key="fruits" />
                </Tabs>
                <Grid
                    columns={2} // 设置列数为2，实现双列布局
                >
                    {_.map(similarGoods, (item, idx) => (
                        <GridItem key={JSON.stringify(item)}>
                            <GoodsBlock
                                key={JSON.stringify(item) + idx}
                                title={item.title}
                                url={item.pict_url}
                                item={item}
                            />
                        </GridItem>
                    ))}
                </Grid>

                <div className={`bottom-btns platform flex`}>
                    <div className="icon-box flex">
                        <Button className="item btn" onClick={() => {}}>
                            <Icon className="yq-iconshouye-zhihui" size={28} />
                            <div className="txt">首页</div>
                        </Button>
                        <Button
                            className="item btn"
                            // onClick={() => !flags && Taro.showToast({title: "功能未开放", icon: "error"})}
                            // openType="share"
                        >
                            <Icon className="yq-iconfenxiang" size={28} />
                            <div className="txt">分享</div>
                        </Button>
                        <Button className="item btn" onClick={copyKL}>
                            <Icon className="yq-iconfuzhi" size={28} />
                            <div className="txt">口令</div>
                        </Button>
                    </div>
                    <div className="price-box fl">
                        <div className="go" onClick={copyKL}>
                            <div className={`txt ${couponInfo.coupon_amount ? "" : "price"}`}>免费领取</div>
                            {couponInfo.coupon_amount && (
                                <div className="price">&nbsp;省￥{couponInfo.coupon_amount}</div>
                            )}
                        </div>
                    </div>
                </div>
            </>
        </Container>
    );
}
